package com.microcore.service;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.microcore.dao.mapper.InvokeTriggerMapper;
import com.microcore.entity.InvokeTrigger;
import com.microcore.entity.param.InvokeParams;
import com.microcore.entity.param.TriggerParams;
import com.microcore.util.DateUtil;

@Service
public class TriggerService {

	@Autowired
    private InvokeTriggerMapper triggerMapper;
	
	/**
     * 给调度添加多个trigger
	 * @author yegui  
	 * @date 2019年1月4日  
	 * @param triggers
	 * void
	 */
	public void addTriggers(String fkId, InvokeParams invokeParams, String params) throws Exception {
		for (TriggerParams trigger : invokeParams.getTriggers()) {
			addTrigger(trigger, fkId, params);
		}
		
	}
    

	/**
	 * 添加单个trigger
	 * @param invokeTrigger
	 * @param fkId
	 * @param params
	 * @return
	 * @throws Exception
	 */
    public String addTrigger(TriggerParams invokeTrigger, String fkId, String params) throws Exception {
    	InvokeTrigger trigger = new InvokeTrigger();
    	trigger.setFkId(fkId);
    	trigger.setInvokeTriggerId(UUID.randomUUID().toString());
    	trigger.setStartDatetime(DateUtil.formatStr(invokeTrigger.getStartTime()));
    	trigger.setEndDatetime(DateUtil.formatStr(invokeTrigger.getEndTime()));
    	trigger.setCount(invokeTrigger.getCount());
    	trigger.setInterval(invokeTrigger.getInterval());
    	trigger.setParams(params);
    	String uuid = UUID.randomUUID().toString();
    	if (invokeTrigger.isSpecial()) {
    		trigger.setTriggerName("#" + uuid);
    	} else {
    		trigger.setTriggerName(uuid);
    	}
    	triggerMapper.insertSelective(trigger);
		return trigger.getInvokeTriggerId();
	}
	
	/**
     * 查询调度的trigger
     * @param taskInvokeId
     * @return
     */
	public List<InvokeTrigger> getTriggersByInvokeId(String taskInvokeId) {
		return triggerMapper.getTriggersByInvokeId(taskInvokeId);
	}

	/**
	 * 更新trigger
	 * @param trigger
	 * @return
	 */
	public int updateTrigger(InvokeTrigger trigger) {
		return triggerMapper.updateByPrimaryKeySelective(trigger);
	}
	
	/**
	 * 删除调度
	 * @param invokeTriggerId
	 * @return
	 */
	public int deleteByPrimaryKey(String invokeTriggerId) {
		return triggerMapper.deleteByPrimaryKey(invokeTriggerId);
	}
}
